import { getLogin } from "@/api/login";
import { openWin } from "@/utils/index";
import { setInfo, setLoginNo, setLoginPwd, setToken, setTokenTime } from "@/utils/auth";
import { Toast } from "vant";
import dayjs from 'dayjs';

const state = {
    userInfo: "",
};

const mutations = {
    SET_TOKEN: (state, userInfo) => {
        state.userInfo = userInfo;
    },
};

const actions = {
    // user login
    login({ commit }, loginInfo) {
        return new Promise(() => {
            getLogin(loginInfo, function(res) {
                if (res.permission.indexOf('100101') != -1) {
                    res.roles += ',' + '100101'
                }
                if (res.permission.indexOf('100103') != -1) {
                    res.roles += ',' + '100103'
                }
                let userInfo = {
                    accessToken: res.accessToken,
                    userId: res.userId,
                    realName: res.realName,
                    platform: res.platform,
                    secret: res.secret,
                    roles: res.roles,
                };
                commit("SET_TOKEN", userInfo);
                setToken(res.accessToken);
                setTokenTime(dayjs().valueOf())
                setInfo(userInfo);
                setLoginNo(loginInfo.no);
                setLoginPwd(loginInfo.pwd);
                Toast({
                    type: "success",
                    message: "登录成功",
                    duration: 500,
                    onClose: () => {
                        openWin("yarn-weaving")
                    }
                });
            });
        });
    },
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
};